package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import object.TradeAddr;
import object.Transaction;
import object.UserCenter;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import pojo.Commodity;
import pojo.LogIncome;
import pojo.LogNoruserbill;
import pojo.TransactionAddr;
import pojo.TransactionDetails;
import pojo.TransactionLog;
import service.Transaction2appService;
import sun.misc.BASE64Decoder;
import utils.MD5Helper;
import utils.OrderNumUtil;
import utils.alipay.config.AlipayConfig;
import utils.alipay.util.AlipayNotify;
import utils.alipay.util.AlipaySubmit;
import utils.alipay.util.UtilDate;
import utils.weixin.WeixinUtil;
import config.ConstantConfig;
import config.SysConfig;

/**
 * 
 * @author zgy
 *
 */
@Controller
@RequestMapping("transaction2app")
public class Transaction2appController {

	@Autowired
	private Transaction2appService transaction2appService;
	
	private static Logger logger = Logger.getLogger(Transaction2appController.class);
	/**
	 * 0001接口
	 * 下发商品列表
	 * @param curPage
	 * @param pageSize
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryCommodity")
//	@ResponseBody
	public String queryCommodity(
			@RequestParam(value = "curPage", defaultValue = "1") Integer curPage,
			@RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize,
			HttpServletRequest req) {
		List<Commodity> commodities = null;
		try {
			commodities = transaction2appService.queryCommodity(curPage, pageSize);
			logger.info("商品列表------"+commodities);
			req.setAttribute("responseCode", "00000");
			req.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			req.setAttribute("commodityList", commodities);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			req.setAttribute("responseCode", "E0001");
			req.setAttribute("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return "forward:/web2app/index/homeAjax.jsp";
	}
	
	/**
	 * 0002接口
	 * 下发交易地址列表
	 * @param platformId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryTradeAddr")
//	@ResponseBody
	public String queryTradeAddr(
			@RequestParam("platformId") String platformId,
			HttpServletRequest req) {
		
		List<TradeAddr> tradeAddrs = null;
		
		try {
			tradeAddrs = transaction2appService.queryTradeAddr(platformId);
			logger.info("交易地址列表------"+tradeAddrs);
			req.setAttribute("responseCode", "00000");
			req.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			req.setAttribute("tradeAddrList", tradeAddrs);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			req.setAttribute("responseCode", "E0001");
			req.setAttribute("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return "forward:/web2app/person/addrmanageAjax.jsp";
	}
	
	
	@RequestMapping("querySingleTradeAddr")
	@ResponseBody
	public HashMap<String, Object> querySingleTradeAddr(
			@RequestParam("platformId") String platformId,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		List<TradeAddr> tradeAddrs = null;
		
		try {
			tradeAddrs = transaction2appService.queryTradeAddr(platformId);
			logger.info("交易地址列表------"+tradeAddrs);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("tradeAddrList", tradeAddrs);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0003接口
	 * 交易订单提交
	 * @param platformId
	 * @param receiveAddr
	 * @param sendAndReceiveType
	 * @param receiveOrderTimeStart
	 * @param sendOrderTimeEnd
	 * @param sendOrderTimeStart
	 * @param receiveOrderTimeEnd
	 * @param comment
	 * @param commodityIds
	 * @param goodsNums
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("commitTransaction")
	@ResponseBody
	public HashMap<String, Object> commitTransaction(
			@RequestParam("platformId") String platformId,
			@RequestParam("receiveAddr") String receiveAddr,
			@RequestParam("sendAndReceiveType") String sendAndReceiveType,
			@RequestParam("receiveOrderTimeStart") Timestamp receiveOrderTimeStart,
			@RequestParam("sendOrderTimeEnd") Timestamp sendOrderTimeEnd,
			@RequestParam("sendOrderTimeStart") Timestamp sendOrderTimeStart,
			@RequestParam("receiveOrderTimeEnd") Timestamp receiveOrderTimeEnd,
			@RequestParam("comment") String comment,
			@RequestParam("commodityIds") String commodityIds,
			@RequestParam("goodsNums") String goodsNums,
			@RequestParam("totalNums") Integer totolNums,
			@RequestParam("totalPrice") BigDecimal totolPrice,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.Transaction transaction = new pojo.Transaction();
		try {
			transaction.setReceiveAddr(java.net.URLDecoder.decode(receiveAddr, "UTF-8"));
			transaction.setSendAndReceiveType(sendAndReceiveType);
			transaction.setReceiveOrderTimeStart(receiveOrderTimeStart);
			transaction.setSendOrderTimeEnd(sendOrderTimeEnd);
			transaction.setSendOrderTimeStart(sendOrderTimeStart);
			transaction.setReceiveOrderTimeEnd(receiveOrderTimeEnd);
			transaction.setStartTime(new Timestamp(System.currentTimeMillis()));
			transaction.setTotalNums(totolNums);
			transaction.setPaymentPrice(totolPrice);
			transaction.setCheck(ConstantConfig.TRANSACTION_CHECK_NO);
			if(BigDecimal.ZERO.compareTo(totolPrice)==0){
				transaction.setPayment(ConstantConfig.TRANSACTION_PAMENT_FREE);
			}else{
				transaction.setPayment(ConstantConfig.TRANSACTION_PAMENT_NOPAY);
			}
			transaction.setOrderNum(OrderNumUtil.createTradeNumber());
			transaction.setStatus(ConstantConfig.TRANSACTION_STATUS_ORDER);
			transaction.setComment(java.net.URLDecoder.decode(comment, "UTF-8"));
			boolean result = false;
			result = transaction2appService.commitTransaction(transaction,platformId,commodityIds,goodsNums);
//			http://service.24box.cn/ybhttpapiAction!startProcess?processId=register-1&apt.title=App寄件&apt.type=1-3-代理商管理员,[text=text]&apt.applicant.orgType=1&apt.applicant.agentId=1&apt.applicant.orgId=1&apt.applicant.orgName=邮宝代理商&apt.applicant.userType=user&apt.applicant.userId=2&apt.applicant.userName=123
//			WeixinUtil.httpRequest(SysConfig.showMsgBox_url, "POST", "processId=register-1"
//					+ "&apt.title=邮宝洗衣&apt.type=1-3-代理商管理员,[textAndUrl=text]"
//					+ "&apt.applicant.orgType=1&apt.applicant.agentId=1&apt.applicant.orgId=1"
//					+ "&apt.applicant.orgName=邮宝代理商&apt.applicant.userType=user"
//					+ "&apt.applicant.userId=2&apt.applicant.userName=123");
			logger.info("交易提交结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.INSERT_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.INSERT_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	
	/**
	 * 0004接口
	 * 交易订单查询
	 * @param orderNum
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryTransaction")
	@ResponseBody
	public HashMap<String, Object> queryTransaction(
			@RequestParam("platformId") String platformId,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		List<Transaction> transactions = null;
		
		try {
			transactions = transaction2appService.queryTransaction(platformId);
			logger.info("交易订单查询------"+transactions);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("transactionList", transactions);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0005接口
	 * 交易订单明细
	 * @param orderNum
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryTransactionDetails")
//	@ResponseBody
	public String queryTransactionDetails(
			@RequestParam("orderNum") String orderNum,
			HttpServletRequest req) {
		
		List<TransactionDetails> transactionDetails = null;
		int totalNum = 0;
		BigDecimal totalPrice = BigDecimal.ZERO;
		try {
			transactionDetails = transaction2appService.queryTransactionDetail(orderNum);
			logger.info("交易订单详情------"+transactionDetails);
			req.setAttribute("responseCode", "00000");
			req.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			req.setAttribute("orderNum", orderNum);
			req.setAttribute("transactionDetails", transactionDetails);
			for(TransactionDetails t:transactionDetails){
				totalNum+=t.getGoodsNum();
				totalPrice=totalPrice.add(t.getGoodsPrice().multiply(new BigDecimal(t.getGoodsNum())));
			}
			req.setAttribute("totalNum", totalNum);
			req.setAttribute("totalPrice", totalPrice);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			req.setAttribute("responseCode", "E0001");
			req.setAttribute("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return "forward:/web2app/order/detailAjax.jsp";
	}
	
	/**
	 * 0006接口
	 * 订单流程跟踪
	 * @param orderNum
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryTransactionLog")
	@ResponseBody
	public HashMap<String, Object> queryTransactionLog(
			@RequestParam("orderNum") String orderNum,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		List<TransactionLog> transactionLogs = null;
		
		try {
			transactionLogs = transaction2appService.queryTransactionLog(orderNum);
			logger.info("交易订单流程------"+transactionLogs);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("orderNum", orderNum);
			response.put("transactionLogs", transactionLogs);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0007接口
	 * 个人中心查询
	 * @param platformId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryUserCenter")
	//@ResponseBody
	public String queryUserCenter(
			@RequestParam("platformId") String platformId,
			@RequestParam("price") BigDecimal price,
			@RequestParam("orderNum") String orderNum,
			@RequestParam("curPage") String curPage,
			HttpServletRequest httpRequest) {
		
		//HashMap<String, Object> response = new HashMap<>();
		UserCenter userCenter = null;
		
		try {
			userCenter = transaction2appService.queryUserCenter(platformId);
	/*		byte[] bs=userCenter.getIcon();
			BASE64Encoder encoder = new BASE64Encoder();
			String icon="";
			if(bs!=null){
				icon="data:image/png;base64,"+encoder.encode(bs);
			}
			logger.info("个人中心查询------"+userCenter);*/
			httpRequest.setAttribute("responseCode", "00000");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			httpRequest.setAttribute("balance", userCenter.getBalance());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			httpRequest.setAttribute("responseCode", "E0001");
			httpRequest.setAttribute ("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return "forward:/web2app/person/payOrder.jsp?price="+price+"&orderNum="+orderNum+"&curPage="+curPage;
	}
	
	/**
	 * 0008接口
	 * 交易订单修改
	 * @param orderNum
	 * @param commodityIds
	 * @param goodsNums
	 * @param totolNums
	 * @param totolPrice
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("updateTrade")
	@ResponseBody
	public HashMap<String, Object> updateTrade(
			@RequestParam("platformId") String platformId,
			@RequestParam("orderNum") String orderNum,
			@RequestParam("commodityIds") String commodityIds,
			@RequestParam("goodsNums") String goodsNums,
			@RequestParam("totolNums") Integer totolNums,
			@RequestParam("totolPrice") BigDecimal totolPrice,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.Transaction transaction = new pojo.Transaction();

		transaction.setOrderNum(orderNum);
		transaction.setTotalNums(totolNums);
		transaction.setPaymentPrice(totolPrice);
		boolean result = false;
		try {
			result = transaction2appService.updateTransaction(transaction,platformId,commodityIds,goodsNums);
			logger.info("交易修改结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.UPDATE_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.UPDATE_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0009接口
	 * 新增交易地址
	 * @param platformId
	 * @param province
	 * @param city
	 * @param area
	 * @param street
	 * @param addr
	 * @param status
	 * @param mobileNum
	 * @param name
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("addTradeAddr")
	@ResponseBody
	public HashMap<String, Object> addTradeAddr(
			@RequestParam("platformId") String platformId,
			@RequestParam("province") String province,
			@RequestParam("city") String city,
			@RequestParam("area") String area,
			@RequestParam("street") String street,
			@RequestParam("addr") String addr,
			@RequestParam("status") String status,
			@RequestParam("mobileNum") String mobileNum,
			@RequestParam("name") String name,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.TransactionAddr transactionAddr = new TransactionAddr();
		
		try {
			transactionAddr.setProvince(java.net.URLDecoder.decode(province, "UTF-8"));
			transactionAddr.setCity(java.net.URLDecoder.decode(city, "UTF-8"));
			transactionAddr.setArea(java.net.URLDecoder.decode(area, "UTF-8"));
			transactionAddr.setStreet(java.net.URLDecoder.decode(street, "UTF-8"));
			transactionAddr.setAddr(java.net.URLDecoder.decode(addr, "UTF-8"));
			transactionAddr.setStatus(status);
			transactionAddr.setMobileNum(mobileNum);
			transactionAddr.setName(java.net.URLDecoder.decode(name, "UTF-8"));
			transactionAddr.setAddrType(ConstantConfig.TRANSACTION_ADDRESS_TYPE_SEND);
			
			boolean result = false;
			if("2".equals(status)){
				result=transaction2appService.clearAddrStatus(platformId);
				logger.info("重置交易地址结果------"+result);
			}
			result = transaction2appService.insertTradeAddr(transactionAddr,platformId);
			logger.info("新增交易地址结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.INSERT_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.INSERT_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	
	/**
	 * 0010接口
	 * 修改交易地址
	 * @param addrID
	 * @param province
	 * @param city
	 * @param area
	 * @param street
	 * @param addr
	 * @param status
	 * @param mobileNum
	 * @param name
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("updateTradeAddr")
	@ResponseBody
	public HashMap<String, Object> updateTradeAddr(
			@RequestParam("platformId") String platformId,
			@RequestParam("addrID") Integer addrID,
			@RequestParam("province") String province,
			@RequestParam("city") String city,
			@RequestParam("area") String area,
			@RequestParam("street") String street,
			@RequestParam("addr") String addr,
			@RequestParam("status") String status,
			@RequestParam("mobileNum") String mobileNum,
			@RequestParam("name") String name,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.TransactionAddr transactionAddr = new TransactionAddr();
		
		try {
			transactionAddr.setAddrId(addrID);
			transactionAddr.setProvince(java.net.URLDecoder.decode(province, "UTF-8"));
			transactionAddr.setCity(java.net.URLDecoder.decode(city, "UTF-8"));
			transactionAddr.setArea(java.net.URLDecoder.decode(area, "UTF-8"));
			transactionAddr.setStreet(java.net.URLDecoder.decode(street, "UTF-8"));
			transactionAddr.setAddr(java.net.URLDecoder.decode(addr, "UTF-8"));
			transactionAddr.setStatus(status);
			transactionAddr.setMobileNum(mobileNum);
			transactionAddr.setName(java.net.URLDecoder.decode(name, "UTF-8"));
			
			boolean result = false;
			if("2".equals(status)){
				result=transaction2appService.clearAddrStatus(platformId);
				logger.info("重置交易地址结果------"+result);
			}
			result = transaction2appService.updateTradeAddr(transactionAddr);
			logger.info("修改交易地址结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.UPDATE_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.UPDATE_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	
	/**
	 * 0011接口
	 * 删除交易地址
	 * @param addrID
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("deleteTradeAddr")
	@ResponseBody
	public HashMap<String, Object> deleteTradeAddr(
			@RequestParam("addrID") Integer addrID,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.TransactionAddr transactionAddr = new TransactionAddr();
		
		transactionAddr.setAddrId(addrID);
		
		boolean result = false;
		try {
			result = transaction2appService.deleteTradeAddr(transactionAddr);
			logger.info("删除交易地址结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.DELETE_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.DELETE_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0012接口
	 * 订单完成列表
	 * @param platformId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("completeTrade")
//	@ResponseBody
	public String completeTrade(
			@RequestParam("platformId") String platformId,
			@RequestParam(value = "flag", defaultValue = "complete") String flag,
			@RequestParam(value = "orderNum", defaultValue = "null") String orderNum,
			HttpServletRequest req) {
		
		List<Transaction> transactions = null;
		
		try {
			transactions = transaction2appService.queryCompleteTrade(platformId);
			logger.info("已完成订单列表------"+transactions);
			req.setAttribute("responseCode", "00000");
			req.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			req.setAttribute("flag", flag);
			req.setAttribute("orderNum", orderNum);
			req.setAttribute("completeTradeList", transactions);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			req.setAttribute("responseCode", "E0001");
			req.setAttribute("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return "forward:/web2app/order/completedAjax.jsp";
	}
	
	/**
	 * 0014接口
	 * 取消订单
	 * @param orderNum
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("cancelTrade")
	@ResponseBody
	public HashMap<String, Object> cancelTrade(
			@RequestParam("orderNum") String orderNum,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.Transaction transaction = new pojo.Transaction();
		
		transaction.setOrderNum(orderNum);
		
		boolean result = false;
		try {
			result = transaction2appService.cancelTransaction(transaction);
			logger.info("取消交易订单结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.DELETE_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.DELETE_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	/**
	 * 0015接口
	 * 用户注册验证
	 * @param openid
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("isUserRegistered")
	@ResponseBody
	public HashMap<String, Object> isUserRegistered(
			@RequestParam("code") String code,
			@RequestParam("sign") String sign,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		boolean result = false;
		try {
			String mobileNum=decrypt(code,sign);
			result = transaction2appService.isUserRegistered(mobileNum);
			//logger.info("验证用户注册结果结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.QUERY_SUCCESS);
				response.put("platformId", mobileNum);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.QUERY_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
//======================================微信相关方法===========================================	
	
	
	/**
	 * 0013/0017接口
	 * 支付宝支付的方法调用
	 * @param out_trade_no
	 * @param total_fee
	 * @param body
	 * @param openid
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("aliPayApi")
	//@ResponseBody
	public String aliPayApi(
			@RequestParam("out_trade_no") String out_trade_no,
			@RequestParam("total_fee") int total_fee,
			@RequestParam("openid") String openid,
			@RequestParam("curPage") String curPage,
			HttpServletRequest httpRequest,HttpServletResponse httpResponse) {
		httpResponse.setContentType("text/html;charset=UTF-8");   
		httpResponse.setCharacterEncoding("UTF-8");
		PrintWriter out;
		try {
			if(!"undefined".equals(openid)&&!"null".equals(openid)&&!"".equals(openid)&&openid!=null){
				out = httpResponse.getWriter();
				String ALIPAY_GATEWAY_NEW = SysConfig.ALIPAY_GATEWAY_NEW;
				String format = "xml";
				String v = "2.0";
				String req_id = UtilDate.getOrderNum();
				String notify_url = SysConfig.ali_notify_url;
				String call_back_url = SysConfig.ali_call_back_url;
				String merchant_url = SysConfig.ali_merchant_url;
				String subject = "youboxO2O";
				String req_dataToken = "<direct_trade_create_req>"
						+ "<notify_url>" + notify_url + "</notify_url>"
						+ "<call_back_url>" + call_back_url + "</call_back_url>"
						+ "<seller_account_name>" + AlipayConfig.seller_email + "</seller_account_name>"
						+ "<out_trade_no>" + out_trade_no+"-"+openid +"-"+curPage+ "</out_trade_no>"
						+ "<subject>" + subject + "</subject>"
						+ "<total_fee>"+total_fee+"</total_fee>"
						+ "<merchant_url>" + merchant_url + "</merchant_url>"
					+ "</direct_trade_create_req>";
				Map<String, String> sParaTempToken = new HashMap<String, String>();
				sParaTempToken.put("service", "alipay.wap.trade.create.direct");
				sParaTempToken.put("partner", AlipayConfig.partner);
				sParaTempToken.put("_input_charset", AlipayConfig.input_charset);
				sParaTempToken.put("sec_id", AlipayConfig.sign_type);
				sParaTempToken.put("format", format);
				sParaTempToken.put("v", v);
				sParaTempToken.put("req_id", req_id);
				sParaTempToken.put("req_data", req_dataToken);
				String sHtmlTextToken = AlipaySubmit.buildRequest(ALIPAY_GATEWAY_NEW,"", "",sParaTempToken);
				sHtmlTextToken = URLDecoder.decode(sHtmlTextToken,AlipayConfig.input_charset);
				String request_token = AlipaySubmit.getRequestToken(sHtmlTextToken);
				String req_data = "<auth_and_execute_req><request_token>" + request_token + "</request_token></auth_and_execute_req>";
				Map<String, String> sParaTemp = new HashMap<String, String>();
				sParaTemp.put("service", "alipay.wap.auth.authAndExecute");
				sParaTemp.put("partner", AlipayConfig.partner);
				sParaTemp.put("_input_charset", AlipayConfig.input_charset);
				sParaTemp.put("sec_id", AlipayConfig.sign_type);
				sParaTemp.put("format", format);
				sParaTemp.put("v", v);
				sParaTemp.put("req_data", req_data);
				String sHtmlText = AlipaySubmit.buildRequest(ALIPAY_GATEWAY_NEW, sParaTemp, "get", "确认");
				transaction2appService.insertLogBill(openid, out_trade_no, new BigDecimal(total_fee));
				out.println(sHtmlText);
				//记录支付、充值记录
				return null;
			}else{
				httpRequest.setAttribute("returnlMsg", "参数异常");
				return "forward:/web2app/returnMsg.jsp";
			}
		}catch (Exception e) {
			httpRequest.setAttribute("returnlMsg", "错误异常");
			return "forward:/web2app/returnMsg.jsp";
		}
	}
		
	/**
	 * 0018接口
	 * 支付宝同步回调
	 * @param out_trade_no
	 * @param total_fee
	 * @param body
	 * @param openid
	 * @param httpRequest
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("aliPayCallBack")
	public String aliPayCallBack(HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws UnsupportedEncodingException {
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = httpRequest.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		String result = new String(httpRequest.getParameter("result").getBytes("ISO-8859-1"),"UTF-8");
		boolean verify_result = AlipayNotify.verifyReturn(params);
		if(verify_result){//验证成功
			String out_trade_no = new String(httpRequest.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
			String curPage=out_trade_no.split("-")[2];
			return "redirect:/index2app.jsp?toPage=1&curPage="+curPage;
		}else{
			httpRequest.setAttribute("returnlMsg", "支付跳转异常");
			return "forward:/web2app/returnMsg.jsp";
		}
		
	}
	

	/**
	 * 支付宝异步支付通知
	 * @param httpRequest
	 * @param httpResponse
	 * @throws DocumentException 
	 */
	@RequestMapping("aliPayed")
	//@ResponseBody
	public void aliPayed(HttpServletRequest httpRequest,HttpServletResponse httpResponse) {
		//获取支付宝POST过来反馈信息
		PrintWriter out ;
		try {
			out = httpResponse.getWriter();
			Map<String,String> params = new HashMap<String,String>();
			Map requestParams = httpRequest.getParameterMap();
			for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i]
							: valueStr + values[i] + ",";
				}
				//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
				//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
				params.put(name, valueStr);
			}
			//RSA签名解密
		   	if(AlipayConfig.sign_type.equals("0001")) {
		   		params = AlipayNotify.decrypt(params);
		   	}
			//XML解析notify_data数据
			Document doc_notify_data = DocumentHelper.parseText(params.get("notify_data"));
			String out_trade_no = doc_notify_data.selectSingleNode( "//notify/out_trade_no" ).getText();
			String outTradeNo = doc_notify_data.selectSingleNode( "//notify/trade_no" ).getText();
			String total_fee = doc_notify_data.selectSingleNode( "//notify/total_fee" ).getText();
			String trade_status = doc_notify_data.selectSingleNode( "//notify/trade_status" ).getText();
			String openId=out_trade_no.split("-")[1];
			if(AlipayNotify.verifyNotify(params)){//验证成功
				if(trade_status.equals("TRADE_FINISHED")){
					transaction2appService.updateTransactionStatus(openId, out_trade_no.split("-")[0], outTradeNo, new BigDecimal(total_fee));
					out.println("success");	//请不要修改或删除
				} else if (trade_status.equals("TRADE_SUCCESS")){
					transaction2appService.updateTransactionStatus(openId, out_trade_no.split("-")[0], outTradeNo,new BigDecimal(total_fee));
					out.println("success");	//请不要修改或删除
				}
			}else{//验证失败
				out.println("fail");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
//=====================================邮宝账户支付===========================================	
	/**
	 * 0019接口
	 * 邮宝账户支付的方法调用
	 * @param out_trade_no
	 * @param total_fee
	 * @param body
	 * @param openid
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("ybPayApi")
	@ResponseBody
	public  HashMap<String, Object> ybPayApi(
			@RequestParam("out_trade_no") String out_trade_no,
			@RequestParam("total_fee") int total_fee,
			@RequestParam("openid") String openid,
			@RequestParam("curPage") String curPage) {
		HashMap<String, Object> response = new HashMap<>();
		try {
			if(transaction2appService.ybPayTransaction(openid, out_trade_no, new BigDecimal(total_fee))){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.PAY_SUCCESS);
				response.put("responseURL", SysConfig.notify_url_yb2app+curPage);
			}else{
				response.put("responseCode", "E0001");
				response.put("response", ConstantConfig.PAY_FAILED);
			}
			
		} catch (Exception e) {
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.PAY_FAILED);
		}
		return response;
	}
	
	/**
	 * 0020接口
	 * 收入接口
	 * @param userId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("incomeList")
	public  String incomeList(
			@RequestParam("userId") Integer userId,HttpServletRequest httpRequest) {
		try {
			List<LogIncome> incomeList=transaction2appService.queryIncomeList(userId);
			httpRequest.setAttribute("responseCode", "00000");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			httpRequest.setAttribute("incomeList", incomeList);
			
		} catch (Exception e) {
			e.printStackTrace();
			httpRequest.setAttribute("responseCode", "E0001");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_FAILED);
		}
		return "forward:/web/person/income.jsp";
	}
	
	/**
	 * 0021接口
	 * 支出接口
	 * @param userId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("userBillList")
	public  String userBillList(
			@RequestParam("userId") Integer userId,HttpServletRequest httpRequest) {
		try {
			List<LogNoruserbill> userBillList=transaction2appService.queryUserBillList(userId);
			httpRequest.setAttribute("responseCode", "00000");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			httpRequest.setAttribute("userBillList", userBillList);
			
		} catch (Exception e) {
			httpRequest.setAttribute("responseCode", "E0001");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_FAILED);
		}
		return "forward:/web/person/pay.jsp";
	}
	
	
	
	private String  decrypt(String code,String sign) throws IOException{
		String mobileNum=null;
		String isign=MD5Helper.getMD5Str(code+"&"+SysConfig.agent_key);
		if(isign.equalsIgnoreCase(sign)){
			BASE64Decoder decoder=new BASE64Decoder();
			String icode=new String(decoder.decodeBuffer(code),"utf-8");
			mobileNum= icode.split("&")[1];
		}
		return mobileNum;
	}
	
}